﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Base;
using Modules.FaceScan.Entitys;
using Modules.FaceScan.Repositories;
using PmSoft;
using PmSoft.Exceptions;
using PmSoft.FileStorage;

namespace Modules.FaceScan;

/// <summary>
/// 人脸照片业务逻辑类
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class FacePhotoService
{
    private readonly IFileStorage fileStorage;
    private readonly FacePhotoRepository facePhotoRepository;

    public FacePhotoService(IFileStorage fileStorage,
        FacePhotoRepository facePhotoRepository)
    {
        this.fileStorage = fileStorage;
        this.facePhotoRepository = facePhotoRepository;
    }

    public FacePhoto? GetPersonFaceByIdCard(string idCard)
    {
        return facePhotoRepository.GetPersonFaceByIdCard(idCard);
    }

    public IEnumerable<FacePhoto> GetPersonFacesByIdCards(IEnumerable<string> idCards)
    {
        return facePhotoRepository.GetPersonFacesByIdCards(idCards);
    }

    public FacePhoto? GetPersonFace(string id)
    {
        return facePhotoRepository.Get(id);
    }

    public void Insert(FacePhoto entity)
    {
        entity.Id = Guid.NewGuid().ToString();
        if (facePhotoRepository.ExistsByIdCard(entity, null))
            throw new BusinessException($"身份证号：{entity.IdCard}  已存在，不能创建");
        facePhotoRepository.Insert(entity);
    }

    public void Update(FacePhoto entity)
    {
        if (facePhotoRepository.ExistsByIdCard(entity, entity.Id))
            throw new BusinessException($"身份证号：{entity.IdCard}  已存在，不能编辑身份证");
        facePhotoRepository.Update(entity);
    }

    public void Delete(int id)
    {
        facePhotoRepository.DeleteByEntityId(id);
    }

    /// <summary>
    /// 获取身份证照片数据
    /// </summary>
    /// <param name="idCard"></param>
    /// <returns></returns>
    /// <exception cref="BusinessException"></exception>
    public byte[] GetCardPhotoData(string idCard)
    {
        var personFace = GetPersonFaceByIdCard(idCard);
        if (personFace == null)
            throw new BusinessException($"{idCard}未进行身份证采集登记");

        byte[] buffer = fileStorage.GetFileAsync(FileBuckets.Person, personFace.IdCardPhoto).GetAwaiter().GetResult();

        return buffer;
    }

    /// <summary>
    /// 获取核验照片，没有核验照片情况下获取身份证照片
    /// </summary>
    /// <param name="idCard"></param>
    /// <returns></returns>
    /// <exception cref="BusinessException"></exception>
    public byte[] GeVerifyPhotoData(string idCard)
    {
        var personFace = GetPersonFaceByIdCard(idCard);
        if (personFace == null)
            throw new BusinessException($"{idCard}未进行身份证采集登记");

        string photoPath = string.IsNullOrEmpty(personFace.VerifyPhoto) ? personFace.IdCardPhoto : personFace.VerifyPhoto;

        byte[] buffer = fileStorage.GetFileAsync(FileBuckets.Person, photoPath).GetAwaiter().GetResult();

        return buffer;
    }
}